import path from "path";
import url from "url";
import fs from "fs";
import { defineConfig, Plugin } from "vite";
import svgr from "vite-plugin-svgr";
import react from "@vitejs/plugin-react";

const __dirname = path.dirname(url.fileURLToPath(import.meta.url));

export default defineConfig({
  define: {
    __DEV__: process.env.NODE_ENV === "development",
  },
  server: {
    proxy: {
      "/api": {
        target: "http://192.168.0.194:8080",
        // rewrite: (path) => path.replace(/^\/api/, ""),
      },
      "/api/ws": {
        target: "http://192.168.0.194:8080",
        ws: true,
      },
    },
  },
  plugins: [
    react(),
    svgr({
      include: "**/*.svg?jsx",
      svgrOptions: {
        svgoConfig: {
          plugins: [
            {
              name: "preset-default",
              params: {
                overrides: {
                  // viewBox is required to resize SVGs with CSS.
                  // @see https://github.com/svg/svgo/issues/1128
                  removeViewBox: false,
                },
              },
            },
          ],
        },
      },
    }),
    JSXImage(),
  ],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
});

function JSXImage(): Plugin {
  return {
    name: "image-to-JSX",
    transform(code, id, options) {
      if (/\.(png|jpg)\?jsx$/.test(id)) {
        // 打包时缓存
        if (this.cache && this.cache.has(id)) {
          return this.cache.get(id);
        }
        const filename = id.replace(/\?jsx$/, "");
        let url = path
          .normalize(filename)
          .replace(__dirname, "")
          .replaceAll(path.sep, path.posix.sep);

        if (process.env.NODE_ENV === "production") {
          url = `/assets/images/${path.basename(filename)}`;
          this.emitFile({
            type: "asset",
            fileName: url.replace(/^\//, ""),
            source: fs.readFileSync(filename),
          });
        }

        const result = `import { createElement } from "react";
  export default function JSXImage(props) {
  return createElement("img", { src: "${url}", ...props })
}`;
        if (this.cache) {
          this.cache.set(id, result);
        }
        return result;
      }
    },
  };
}
